#include "cupdatedialog.h"
#include <QGridLayout>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>



CUpdateDialog::CUpdateDialog(const QString &tbname, const QSqlRecord &record,  QWidget *parent,const QSqlDatabase db, Qt::WindowFlags f)
:QDialog(parent,f)

{
    //lineedit的容器
    QList<QLineEdit*> leList;

    //创建控件并布局
    QGridLayout *grid =  new QGridLayout(nullptr);
    QVBoxLayout *main = new QVBoxLayout(nullptr);
    QHBoxLayout *hbox = new QHBoxLayout(nullptr);
    for(int i=0;i<record.count();i++)
    {


        //创建label lineedit
        QLabel *lbl = new QLabel(record.fieldName(i));
        QLineEdit *le = new QLineEdit();
        leList.push_back(le);

        //第一个字段必须是ID字段
        if (i == 0){
            le->setEnabled(false);
        }

        le->setMinimumWidth(200);
        le->setText(record.value(i).toString());
        grid->addWidget(lbl,i,0);
        grid->addWidget(le,i,1);
    }

    //创建两个按钮
    QPushButton *btn_ok = new QPushButton("保存");
    QPushButton *btn_exit = new QPushButton("退出");
    hbox->addWidget(btn_exit);
    hbox->addStretch(1);
    hbox->addWidget(btn_ok);

    main->addLayout(grid);
    main->addLayout(hbox);
    this->setLayout(main);

    //信号和槽
    connect(btn_exit,&QPushButton::clicked,this,[=](){

        this->close();
    });

    connect(btn_ok,&QPushButton::clicked,this,[=](){

        //制作sql语句
        QString s1;
        for(int i=1;i<record.count();i++)
        {
            s1+=tr("%1='%2',").arg(record.fieldName(i)).arg(leList.at(i)->text());

        }
        //去掉最后一个逗号
        s1.remove(s1.count()-1,1);

        QString sql = tr("UPDATE %1 SET %2 WHERE ID=%3").arg(tbname,s1,leList[0]->text());
        QSqlQuery query(db);
        bool ret = query.exec(sql);
        if(!ret){
            QMessageBox::information(this,"错误提示",query.lastError().text());
        }else
        {
            QMessageBox::information(this,"成功","数据修改成功!");
            accept();
        }



    });

}
